package net.src.udp_multicast;

import java.net.*;

/**
 * 组播实现原理,组播专用地址:224.0.0.0-239.255.255.255范围内,端口9999
 * 发送端目的地是组播ip,接收端绑定组播ip,端口9999
 * 使用DatagramSocket的子类MulticastSocket实现接收端绑定组播ip
 */
public class ServerDemo {
    public static void main(String[] args) throws Exception {
        //创建组播接收端对象和端口
        MulticastSocket socket = new MulticastSocket(9999);
        //将接收端加入到组播组中去
        socket.joinGroup(InetAddress.getByName("224.0.0.1"));
//        socket.joinGroup(new InetSocketAddress(InetAddress.getByName("224.0.0.1"),9999), NetworkInterface.getByInetAddress(InetAddress.getLocalHost()));

        //创建一个数据包接收数据
        byte[] buffer = new byte[1024*64];
        DatagramPacket packet = new DatagramPacket(buffer,buffer.length);

        System.out.println("客户端启动!");
        //不停接收数据
        while(true){
            socket.receive(packet);
            //获取发送端的ip和端口,获取对方端口,使用数据包的方法getlength获取接收的长度
            System.out.println("收到来自:"+packet.getAddress()+",端口为:"+packet.getPort()+"的消息:"+
                    new String(buffer,0, packet.getLength()));
        }

    }
}
